import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { getcurrentUserMenusApi } from '@/api/menu'
import router, { constantRoutes } from '@/router'
import type { LoginRequest, UserInfo } from '@/types'
import { RouteRecordRaw } from 'vue-router'

// 重置路由函数
export function resetRouter() {
  // 获取所有路由
  const allRoutes = router.getRoutes()
  
  // 删除所有动态添加的路由（不包括常量路由）
  allRoutes.forEach(route => {
    if (route.name && !constantRoutes.some(constantRoute => 
      constantRoute.name === route.name || 
      (constantRoute.children && constantRoute.children.some(child => child.name === route.name))
    )) {
      router.removeRoute(route.name)
    }
  })
}

// 用户状态接口
interface UserState {
  token: string | null
  userInfo: UserInfo | null
  routesLoaded: boolean
  userMenus: any[] | null
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('token') || null)
  const userInfo = ref<UserInfo | null>(null)
  const routesLoaded = ref<boolean>(false)
  const userMenus = ref<any[] | null>(null)
  
  // 登录
  const loginAction = async (loginData: LoginRequest) => {
    try {
      const response = await login(loginData)
      // 现在response直接是后端返回的数据对象 { token: xxx, userInfo: xxx }
      if (response && response.token && response.userInfo) {
        token.value = response.token
        userInfo.value = response.userInfo
        localStorage.setItem('token', response.token)
        return { success: true }
      } else {
        return { success: false, message: '登录响应数据格式错误' }
      }
    } catch (error: any) {
      return { success: false, message: error.message || '登录失败' }
    }
  }
  
  // 退出登录
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      userMenus.value = null
      routesLoaded.value = false
      localStorage.removeItem('token')
      resetRouter()
    }
  }
  
  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const userInfoData = await getUserInfo()
      // 现在直接返回用户信息对象
      if (userInfoData && (userInfoData.id || userInfoData.username)) {
        userInfo.value = userInfoData
        return { success: true }
      } else {
        return { success: false, message: '获取用户信息失败' }
      }
    } catch (error: any) {
      if (error.message === '未授权' || error.message?.includes('401')) {
        return { success: false, message: '登录已过期，请重新登录', code: 401 }
      }
      return { success: false, message: error.message || '获取用户信息失败' }
    }
  }
  
  // 获取用户菜单
  const getUserMenusAction = async () => {
    try {
      const response = await getcurrentUserMenusApi()
      // 对于后端的ResponseEntity返回，前端直接收到菜单数组
      if (Array.isArray(response)) {
        userMenus.value = response
        return { success: true, data: response }
      } else {
        return { success: false, message: '未获取到菜单数据' }
      }
    } catch (error: any) {
      return { success: false, message: error.message || '获取用户菜单失败' }
    }
  }
  
  // 动态添加路由
  const addRoutes = (menus: any[]) => {
    // 将菜单转换为路由配置
    const routes = generateRoutes(menus)
    
    // 将动态路由作为MainLayout的子路由添加
    routes.forEach(route => {
      router.addRoute('Layout', route) // 添加到Layout路由下
    })
  }
  
  // 根据菜单生成路由配置
  const generateRoutes = (menus: any[]): RouteRecordRaw[] => {
    const routes: RouteRecordRaw[] = []
    
    menus.forEach(menu => {
      if (menu.menuType === 1 && menu.path && menu.component) { // 菜单类型
        // 处理组件路径，支持子目录
        let componentImport
        if (menu.component.includes('/')) {
          // 如果包含子目录，需要特殊处理
          const componentPath = menu.component
          if (componentPath === 'system/UserManagement') {
            componentImport = () => import('@/views/system/UserManagement.vue')
          } else if (componentPath === 'system/MenuManagement') {
            componentImport = () => import('@/views/system/MenuManagement.vue')
          } else if (componentPath === 'system/RoleManagement') {
            componentImport = () => import('@/views/system/RoleManagement.vue')
          } else {
            // 默认处理
            componentImport = () => import(`@/views/${menu.component}.vue`)
          }
        } else {
          componentImport = () => import(`@/views/${menu.component}.vue`)
        }
        
        const route: RouteRecordRaw = {
          path: menu.path.startsWith('/') ? menu.path.substring(1) : menu.path, // 移除开头的/，因为是子路由
          name: menu.name,
          component: componentImport,
          meta: {
            title: menu.name,
            icon: menu.icon,
            requiresAuth: true
          }
        }
        routes.push(route)
      }
      
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        const childRoutes = generateRoutes(menu.children)
        routes.push(...childRoutes)
      }
    })
    
    return routes
  }
  
  // 加载用户路由
  const loadUserRoutes = async () => {
    try {
      // 获取用户菜单
      const menuResult = await getUserMenusAction()
      if (!menuResult.success) {
        throw new Error(menuResult.message || '获取菜单失败')
      }
      
      // 添加路由
      if (menuResult.data) {
        addRoutes(menuResult.data)
      }
      
      // 标记路由已加载
      routesLoaded.value = true
      
      return { success: true }
    } catch (error: any) {
      routesLoaded.value = false
      return { success: false, message: error.message || '加载路由失败' }
    }
  }
  
  return {
    token,
    userInfo,
    routesLoaded,
    userMenus,
    loginAction,
    logoutAction,
    getUserInfoAction,
    getUserMenusAction,
    loadUserRoutes
  }
})